import serial
from sys import exit
import time

_blocksize = 16

print "Would you like to encrypt or decrypt? (e/d)"
enc_dec = raw_input()

if 'e' in enc_dec:
    plaintext_filename = "plaintext_enc.txt"
    ciphertext_filename = "ciphertext_enc.txt"
elif 'd' in enc_dec:
    plaintext_filename = "ciphertext_enc.txt"
    ciphertext_filename = "ciphertext_dec.txt"
else:
    print "Incorrect input. Quitting"
    exit()

ser = serial.Serial("COM1", 9600)
infile = open(plaintext_filename, 'r')
outfile = open(ciphertext_filename, 'w')

print "Please enter your key."
key = raw_input()

# Make plaintext length a multiple of 16
plaintext = infile.read()
infile.close()
mod = len(plaintext) % _blocksize
if mod is not 0:
    plaintext += "=" * (_blocksize - mod)

if len(key) < len(plaintext):
    key = key * (int(len(plaintext) / len(key)) + 1)
elif len(key) > len(plaintext):
    key = key[:len(plaintext)]
    print "Key length greater than plaintext length. Eliding key."
else:
    pass

# Break plaintext and key up into 16 char blocks and send
ciphertext = ""
latencies = []
for i in xrange(0, len(plaintext), _blocksize):
    start = time.time()
    ser.write(key[i:i + _blocksize])
    ser.write(plaintext[i:i + _blocksize])
    print key[i:i + _blocksize]
    print plaintext[i:i + _blocksize]
    ciphertext += ser.read(_blocksize)
    latencies.append(time.time() - start)
    
outfile.write(ciphertext)
outfile.close()

if 'e' in enc_dec:
    print "Ciphertext written to " + ciphertext_filename
else:
    print "Decrypted ciphertext written to " + ciphertext_filename

avg_latency = 0
for latency in latencies:
    print latency
    avg_latency += latency

print "Avg latency: %s" %(avg_latency / len(latencies))
